package hbsi.edu.utils;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author 程奕红
 * @version 1.0
 */
public class DBUtil {
    //1.方法能够建立链接，并将连接对象返回，驱动只需要完成一次
    //2.提供方法释放资源
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public  static Connection getConnection() throws SQLException {
        String url="jdbc:mysql:///myjdbc";
        String username="root";
        String password="root";
        return (Connection) DriverManager.getConnection(url,username,password);
    }
    //提供方法释放资源
    public static  void release(Statement statement,Connection connection){
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public  static void release(ResultSet res, Statement statement,Connection connection) throws SQLException {
        if(res!=null){
            res.close();
        }
        if(statement!=null){
            statement.close();
        }
        if(connection!=null){
            connection.close();
        }


    }
}

